package pl.edu.agh.pros.proxy.view.key;

import java.util.Arrays;

import pl.edu.agh.pros.proxy.view.xmpp.XmppServersTable;

import com.vaadin.data.Item;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.TextField;

public class AppKeysForm extends Form {

	private static final long serialVersionUID = -6884510525756826439L;
	private static final String COMMON_FIELD_WIDTH = "15em";
	private static final String LONG_FIELD_WIDTH = "30em";
	private final XmppServersTable xmppServersTable;

	public AppKeysForm(XmppServersTable xmppServersTable) {
		this.xmppServersTable = xmppServersTable;
		this.setCaption("General");
		this.setWriteThrough(false);
		this.setInvalidCommitted(false);
		this.setFormFieldFactory(new KeysFieldFactory());
		this.setVisibleItemProperties(Arrays.asList(new String[] { "name", "xmppServerConfiguration" }));
		this.setWriteThrough(false);
	}

	@SuppressWarnings("serial")
	private class KeysFieldFactory extends DefaultFieldFactory {

		final ComboBox serversCB = new ComboBox("XMPP Server");

		public KeysFieldFactory() {
			serversCB.setWidth(COMMON_FIELD_WIDTH);
			serversCB.setContainerDataSource(xmppServersTable.getContainerDataSource());
			serversCB.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_PROPERTY);
			serversCB.setItemCaptionPropertyId("hostname");
			serversCB.setFilteringMode(ComboBox.FILTERINGMODE_STARTSWITH);
			serversCB.setWidth(COMMON_FIELD_WIDTH);
			serversCB.setRequired(true);
		}

		@Override
		public Field createField(Item item, Object propertyId, Component uiContext) {

			if ("name".equals(propertyId)) {
				TextField tf = new TextField("Name");
				tf.setRequired(true);
				tf.setNullRepresentation("");
				tf.setWidth(COMMON_FIELD_WIDTH);
				return tf;
			} else if ("providerAppKey".equals(propertyId)) {
				TextField tf = new TextField("Provider Key");
				tf.setNullRepresentation("");
				tf.setReadOnly(true);
				tf.setWidth(LONG_FIELD_WIDTH);
				return tf;
			} else if ("clientAppKey".equals(propertyId)) {
				TextField tf = new TextField("Client Key");
				tf.setReadOnly(true);
				tf.setNullRepresentation("");
				tf.setWidth(LONG_FIELD_WIDTH);
				return tf;
			} else if ("xmppServerConfiguration".equals(propertyId)) {
				return serversCB;
			}
			return null;
		}
	}

}
